<?php
include_once("./lib/logger.php");
include_once("./connConfig.php");
class imconfig{
	
	//公钥验签
	public static $platform_publicKey="";

    public static $independent_publicKey="";

	public static $publicKey = "";


   
    /**
     * 解析response报文
     * $content  收到的response报文
     * $pkey     plutus平台公钥，用于验签
     * $respJson 返回解析后的json报文
     * return    解析成功TRUE，失败FALSE
     */
    public static function parseResp($content, $pkey, &$respJson) {
        $arr=explode("&",$content);	
		
		foreach($arr as $k=>$v){
			$str = $v;
			$index = strpos($str,"=",0);
			$key = substr($str,0,$index);
			$val = substr($str,strlen($key)+1,strlen($str)-(strlen($key)));
			$resp[$key] = trim($val);
		}

        //验证签名，失败应答报文没有sign，跳过验签
        if(array_key_exists("signature", $resp)) {
            //校验签名
            //$pkey = self::formatPubKey($pkey);
			$sign = $resp['signature'];
		    unset($resp['signature']);
			ksort($resp);
			$respJson = $resp;
			$content = "";
            foreach($resp as $key=>$val){
		        $content.= $key."=".$val."&";	
		    }
			
			$content = substr($content,0,strlen($content)-1);
			Config::$loggerDebug->debug('parseResp',$content);
			
            return self::verify($content, $sign, $pkey);
			
        } else if(array_key_exists('errmsg', $respJson)) {
            return FALSE;
        }

        return TRUE;
    }
	
	//公钥验签
   public static function verify($data, $sign, $pubKey)  {
        //转换为openssl格式密钥
        $res = openssl_get_publickey($pubKey);
        //调用openssl内置方法验签，返回bool值
        $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA1);
		Config::$loggerDebug->debug('verify',$result);
        //释放资源
        openssl_free_key($res);
        //返回资源是否成功
        return $result;
    }

}
?>
